home *** CD-ROM | disk | FTP | other *** search
- Path: news.cern.ch!danpop
- From: danpop@mail.cern.ch (Dan Pop)
- Newsgroups: comp.lang.c
- Subject: Re: Memory leakage
- Date: 19 Apr 96 00:35:06 GMT
- Organization: CERN European Lab for Particle Physics
- Message-ID: <danpop.829874106@news.cern.ch>
- References: <4l3582$1v@alice.walrus.com>
- NNTP-Posting-Host: ues5.cern.ch
- Mime-Version: 1.0
- Content-Type: text/plain; charset=US-ASCII
- Content-Transfer-Encoding: 7bit
- X-Newsreader: NN version 6.5.0 #18 (NOV)
-
- In <4l3582$1v@alice.walrus.com> warrenj@walrus.com (Warren Johnson) writes:
-
- >Suppose I have a function:
- >
- >int give_number() {
- > ...
- > ...
- > ...
- >}
- >
- >and in main I have a line :
- >
- >if(x>give_number()) {
- > ...
- > ... }
- >
- >Now my question is this: give_number() returns an integer. Obviously
- >the compiler must allocate memory for this integer.
-
- It may be obvious to you, but it's not obvious to most compiler
- implementors, who return that integer in a register :-)
-
- >However, we are not
- >returning this integer to an integer pointer, therefore this allocated
- >memory is floating about in the void somewhere without something pointing
- >to it. Is this memory deallocated when the function is finished running
- >it's course or do i have to do this:
-
- The rule is actually very simple: you care about the memory you
- allocate yourself and let the compiler care about the memory it allocates
- itself. This way, no memory leaks will ever occur.
-
- >y = give_number();
- >
- >if(x>y) { blabalh}
- >
- >free(y); // or just let y be deallocated when the function is over with
-
- This is a gross mistake:
-
- 1. y is not a pointer.
-
- 2. y has not been initialized with the value returned by one of the three
- dynamic allocation functions.
-
- 3. // is a syntax error in C. No conforming C compiler will accept it.
-
- Because of #1, the compiler will simply reject your code (assuming a
- proper prototype for free() is in scope and ignoring the #3 issue).
-
- Dan
- --
- Dan Pop
- CERN, CN Division
- Email: danpop@mail.cern.ch
- Mail: CERN - PPE, Bat. 31 R-004, CH-1211 Geneve 23, Switzerland
-